package com.matt.service.impl;

import com.matt.domain.WorkPlace;
import com.matt.repository.WorkPlaceRepository;
import com.matt.service.WorkPlaceService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;


@Service
public class WorkPlaceServiceImpl implements WorkPlaceService {

    @Autowired
    private WorkPlaceRepository workPlaceRepository;

    @Override
    public Page<WorkPlace> getWorkPlaceList(String areaId, String staffId, String roleCode, Integer apiVersion,  String appid,
                                            Integer pageNum, Integer pageSize) {

        Specification<WorkPlace> specification = new Specification<WorkPlace>() {
            @Override
            public Predicate toPredicate(Root<WorkPlace> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();

                if (StringUtils.isNotBlank(roleCode))
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("roleCode"), roleCode)));

                predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("deleted"),false )));

                if(apiVersion != null) {
                    predicates.add(criteriaBuilder.and(criteriaBuilder.lessThanOrEqualTo(root.get("apiVersion"), apiVersion)));
                }else{
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("apiVersion"), 1)));
                }

                if(appid != null) {
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("appid"), appid)));
                }else{
                    predicates.add(criteriaBuilder.and(criteriaBuilder.isNull(root.get("appid"))));
                }


                query.where(predicates.toArray(new Predicate[predicates.size()]));
                query.orderBy(criteriaBuilder.asc(root.get("orderNum")));
                return query.getRestriction();
            }
        };
        Page<WorkPlace> page = workPlaceRepository.findAll(specification, PageRequest.of(pageNum, pageSize));

        return page;
    }
}
